<template>
  <div class="announce-list">
    <div class="page-header">
      <h2>公告列表</h2>
      <p>管理系统公告</p>
    </div>

    <div class="list-content">
      <div class="list-header">
        <div class="search-box">
          <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索公告..."
              class="search-input"
          />
          <i class="fa fa-search search-icon"></i>
        </div>
        <div class="list-actions">
          <button class="action-btn" @click="refreshList" :disabled="loading">
            <i class="fa fa-refresh"></i>
            {{ loading ? '加载中...' : '刷新' }}
          </button>
        </div>
      </div>

      <div class="announcements">
        <div v-if="loading" class="loading-state">
          <i class="fa fa-spinner fa-spin"></i>
          加载中...
        </div>

        <div v-else-if="filteredAnnouncements.length === 0" class="empty-state">
          <i class="fa fa-inbox"></i>
          <p>暂无公告</p>
        </div>

        <div v-else v-for="item in filteredAnnouncements" :key="item.id" class="announcement-item">
          <div class="announcement-header">
            <h4 class="announcement-title">{{ item.title }}</h4>
            <div class="announcement-meta">
              <span class="announcement-date">{{ formatDate(item.createTime) }}</span>
            </div>
          </div>
          <p class="announcement-content">{{ item.content }}</p>
          <div class="announcement-footer">
            <div class="announcement-status">
              <span class="status-badge" :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </span>
            </div>
            <div class="announcement-actions">
              <button class="edit-btn" @click="editAnnouncement(item)" :disabled="loading">
                <i class="fa fa-edit"></i>
                编辑
              </button>
              <button
                  v-if="item.status === 0"
                  class="publish-btn"
                  @click="publishAnnouncement(item.id)"
                  :disabled="loading"
              >
                <i class="fa fa-bullhorn"></i>
                发布
              </button>
              <button
                  v-if="item.status === 1"
                  class="withdraw-btn"
                  @click="withdrawAnnouncement(item.id)"
                  :disabled="loading"
              >
                <i class="fa fa-undo"></i>
                撤回
              </button>
              <button class="delete-btn" @click="deleteAnnouncement(item.id)" :disabled="loading">
                <i class="fa fa-trash"></i>
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>编辑公告</h3>
          <button class="modal-close" @click="closeEditModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">
              <i class="fa fa-header form-icon"></i>
              公告标题
            </label>
            <input
                v-model="editingAnnouncement.title"
                type="text"
                class="form-input enhanced-input"
                placeholder="请输入公告标题..."
                maxlength="200"
            >
            <div class="input-counter">{{ editingAnnouncement.title?.length || 0 }}/200</div>
          </div>

          <div class="form-group">
            <label class="form-label">
              <i class="fa fa-align-left form-icon"></i>
              公告内容
            </label>
            <div class="textarea-container">
          <textarea
              v-model="editingAnnouncement.content"
              rows="8"
              class="form-textarea enhanced-textarea"
              placeholder="请输入公告内容..."
              maxlength="2000"
          ></textarea>
              <div class="textarea-counter">{{ editingAnnouncement.content?.length || 0 }}/2000</div>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">
              <i class="fa fa-tag form-icon"></i>
              公告类型
            </label>
            <div class="select-container">
              <select v-model="editingAnnouncement.type" class="form-input enhanced-select">
                <option value="运营通知">运营通知</option>
                <option value="课程上新">课程上新</option>
                <option value="系统维护">系统维护</option>
              </select>
              <i class="fa fa-chevron-down select-arrow"></i>
            </div>
          </div>

          <div class="form-group" v-if="editingAnnouncement.createdAt">
            <label class="form-label">
              <i class="fa fa-calendar form-icon"></i>
              创建时间
            </label>
            <div class="readonly-field">{{ formatDate(editingAnnouncement.createdAt) }}</div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-secondary" @click="closeEditModal">
            <i class="fa fa-times"></i>
            取消
          </button>
          <button class="btn-primary" @click="updateAnnouncement" :disabled="loading">
            <i class="fa fa-save"></i>
            {{ loading ? '保存中...' : '保存更改' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'AnnounceList',
  setup() {
    const searchKeyword = ref('')
    const loading = ref(false)
    const showEditModal = ref(false)
    const editingAnnouncement = ref({})

    const announcements = ref([])

    // 从后端获取公告列表
    const fetchAnnouncements = async () => {
      loading.value = true
      try {
        const response = await fetch('http://localhost:8081/api/announcements/all')
        const result = await response.json()

        if (result.code === 200||result.code === 304) {
          announcements.value = result.data || []
        } else {
          alert(result.message || '获取公告列表失败')
        }
      } catch (error) {
        console.error('获取公告列表失败:', error)
        alert('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const filteredAnnouncements = computed(() => {
      if (!searchKeyword.value) {
        return announcements.value
      }
      const keyword = searchKeyword.value.toLowerCase()
      return announcements.value.filter(item =>
          item.title.toLowerCase().includes(keyword) ||
          (item.content && item.content.toLowerCase().includes(keyword)) ||
          (item.publisher && item.publisher.toLowerCase().includes(keyword))
      )
    })

    const editAnnouncement = (item) => {
      editingAnnouncement.value = { ...item }
      showEditModal.value = true
    }

    const closeEditModal = () => {
      showEditModal.value = false
      editingAnnouncement.value = {}
    }

    const updateAnnouncement = async () => {
      if (!editingAnnouncement.value.title || !editingAnnouncement.value.content) {
        alert('请填写标题和内容')
        return
      }

      loading.value = true
      try {
        const response = await fetch('http://localhost:8081/api/announcements/update', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(editingAnnouncement.value)
        })

        const result = await response.json()

        if (result.code === 200) {
          alert('公告更新成功')
          closeEditModal()
          fetchAnnouncements() // 刷新列表
        } else {
          alert(result.message || '更新失败')
        }
      } catch (error) {
        console.error('更新公告失败:', error)
        alert('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const deleteAnnouncement = async (id) => {
      if (!confirm('确定要删除这条公告吗？')) {
        return
      }

      loading.value = true
      try {
        const response = await fetch(`http://localhost:8081/api/announcements/${id}`, {
          method: 'DELETE'
        })

        const result = await response.json()

        if (result.code === 200) {
          alert('公告删除成功')
          fetchAnnouncements() // 刷新列表
        } else {
          alert(result.message || '删除失败')
        }
      } catch (error) {
        console.error('删除公告失败:', error)
        alert('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const publishAnnouncement = async (id) => {
      loading.value = true
      try {
        const response = await fetch(`http://localhost:8081/api/announcements/${id}/publish`, {
          method: 'PUT'
        })

        const result = await response.json()

        if (result.code === 200) {
          alert('公告发布成功')
          fetchAnnouncements() // 刷新列表
        } else {
          alert(result.message || '发布失败')
        }
      } catch (error) {
        console.error('发布公告失败:', error)
        alert('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const withdrawAnnouncement = async (id) => {
      loading.value = true
      try {
        const response = await fetch(`http://localhost:8081/api/announcements/${id}/withdraw`, {
          method: 'PUT'
        })

        const result = await response.json()

        if (result.code === 200) {
          alert('公告撤回成功')
          fetchAnnouncements() // 刷新列表
        } else {
          alert(result.message || '撤回失败')
        }
      } catch (error) {
        console.error('撤回公告失败:', error)
        alert('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const refreshList = () => {
      fetchAnnouncements()
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getStatusClass = (status) => {
      const statusMap = {
        'DRAFT': 'draft',
        'PUBLISHED': 'published',
        'WITHDRAWN': 'withdrawn'
      }
      return statusMap[status] || 'draft'
    }

    const getStatusText = (status) => {
      const statusMap = {
        '0': '草稿',
        '1': '已发布',
      }
      return statusMap[status]
    }

    // 组件挂载时获取数据
    onMounted(() => {
      fetchAnnouncements()
    })

    return {
      searchKeyword,
      announcements,
      filteredAnnouncements,
      loading,
      showEditModal,
      editingAnnouncement,
      editAnnouncement,
      closeEditModal,
      updateAnnouncement,
      deleteAnnouncement,
      publishAnnouncement,
      withdrawAnnouncement,
      refreshList,
      formatDate,
      getStatusClass,
      getStatusText
    }
  }
}
</script>

<style scoped>
/* 增强的表单样式 */
.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
  color: #e2e8f0;
  font-weight: 600;
  font-size: 0.9rem;
}

.form-icon {
  margin-right: 0.5rem;
  color: #667eea;
  width: 16px;
  text-align: center;
}

.enhanced-input, .enhanced-select {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  color: #f8fafc;
}

.enhanced-input:focus, .enhanced-select:focus {
  outline: none;
  border-color: #667eea;
  background-color: rgba(255, 255, 255, 0.08);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.enhanced-input::placeholder {
  color: #64748b;
}

/* 文本区域容器 */
.textarea-container {
  position: relative;
}

.enhanced-textarea {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  color: #f8fafc;
  resize: vertical; /* 允许垂直调整大小 */
  min-height: 120px;
  max-height: 300px; /* 限制文本区域最大高度 */
  font-family: inherit;
  line-height: 1.5;
}

.enhanced-textarea:focus {
  outline: none;
  border-color: #667eea;
  background-color: rgba(255, 255, 255, 0.08);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.enhanced-textarea::placeholder {
  color: #64748b;
}

/* 字符计数器 */
.input-counter, .textarea-counter {
  text-align: right;
  font-size: 0.75rem;
  color: #94a3b8;
  margin-top: 0.25rem;
}

/* 选择框容器 */
.select-container {
  position: relative;
}

.select-arrow {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #64748b;
  pointer-events: none;
}

.enhanced-select {
  appearance: none;
  cursor: pointer;
}

.enhanced-select option {
  background: rgba(15, 23, 42, 0.95);
  color: #f8fafc;
  padding: 0.5rem;
}

/* 只读字段 */
.readonly-field {
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  color: #94a3b8;
  font-size: 0.9rem;
}

/* 按钮图标 */
.btn-primary i, .btn-secondary i {
  margin-right: 0.5rem;
}
.announce-list {
  padding: 0;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h2 {
  color: #f8fafc;
  font-size: 1.8rem;
  margin-bottom: 0.5rem;
}

.page-header p {
  color: #94a3b8;
  font-size: 1rem;
}

.list-content {
  background: rgba(15, 23, 42, 0.6);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-input {
  width: 100%;
  padding: 0.75rem 1rem 0.75rem 2.5rem;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  color: #f8fafc;
}

.search-input::placeholder {
  color: #64748b;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  background-color: rgba(255, 255, 255, 0.08);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.search-icon {
  position: absolute;
  left: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #64748b;
}

.list-actions {
  display: flex;
  gap: 1rem;
}

.action-btn {
  background: rgba(102, 126, 234, 0.15);
  color: #cbd5e0;
  border: 1px solid rgba(102, 126, 234, 0.3);
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.action-btn:hover:not(:disabled) {
  background: rgba(102, 126, 234, 0.25);
  color: white;
  transform: translateY(-1px);
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.announcements {
  display: grid;
  gap: 1rem;
}

.loading-state, .empty-state {
  text-align: center;
  padding: 3rem;
  color: #94a3b8;
}

.loading-state i, .empty-state i {
  font-size: 2rem;
  margin-bottom: 1rem;
  display: block;
}

.announcement-item {
  background: rgba(15, 23, 42, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 1.5rem;
  transition: all 0.3s ease;
}

.announcement-item:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
  transform: translateY(-2px);
  border-color: rgba(102, 126, 234, 0.3);
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.announcement-title {
  color: #f8fafc;
  font-size: 1.2rem;
  margin: 0;
  font-weight: 600;
  flex: 1;
}

.announcement-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 0.25rem;
}

.announcement-date {
  color: #94a3b8;
  font-size: 0.9rem;
}

.announcement-publisher {
  color: #64748b;
  font-size: 0.8rem;
}

.announcement-content {
  color: #e2e8f0;
  line-height: 1.6;
  margin-bottom: 1rem;
  white-space: pre-wrap;
}

.announcement-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.announcement-actions {
  display: flex;
  gap: 0.5rem;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
}

.status-badge.draft {
  background: rgba(156, 163, 175, 0.15);
  color: #9ca3af;
  border: 1px solid rgba(156, 163, 175, 0.3);
}

.status-badge.published {
  background: rgba(34, 197, 94, 0.15);
  color: #4ade80;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-badge.withdrawn {
  background: rgba(245, 158, 11, 0.15);
  color: #f59e0b;
  border: 1px solid rgba(245, 158, 11, 0.3);
}

.edit-btn, .delete-btn, .publish-btn, .withdraw-btn {
  padding: 0.4rem 0.8rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.85rem;
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.edit-btn {
  background: rgba(102, 126, 234, 0.15);
  color: #667eea;
  border: 1px solid rgba(102, 126, 234, 0.3);
}

.edit-btn:hover:not(:disabled) {
  background: rgba(102, 126, 234, 0.25);
  color: white;
}

.delete-btn {
  background: rgba(229, 62, 62, 0.15);
  color: #e53e3e;
  border: 1px solid rgba(229, 62, 62, 0.3);
}

.delete-btn:hover:not(:disabled) {
  background: rgba(229, 62, 62, 0.25);
  color: white;
}

.publish-btn {
  background: rgba(34, 197, 94, 0.15);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.publish-btn:hover:not(:disabled) {
  background: rgba(34, 197, 94, 0.25);
  color: white;
}

.withdraw-btn {
  background: rgba(245, 158, 11, 0.15);
  color: #f59e0b;
  border: 1px solid rgba(245, 158, 11, 0.3);
}

.withdraw-btn:hover:not(:disabled) {
  background: rgba(245, 158, 11, 0.25);
  color: white;
}

.edit-btn:disabled, .delete-btn:disabled, .publish-btn:disabled, .withdraw-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: rgba(15, 23, 42, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh; /* 限制最大高度为视口的80% */
  display: flex;
  flex-direction: column; /* 添加弹性布局 */
  backdrop-filter: blur(20px);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h3 {
  color: #f8fafc;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  color: #94a3b8;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-close:hover {
  color: #e2e8f0;
}

.modal-body {
  padding: 1.5rem;
  overflow-y: auto; /* 添加垂直滚动 */
  flex: 1; /* 占据剩余空间 */
}

/* 确保表单组之间有合适的间距 */
.form-group {
  margin-bottom: 1.5rem;
}
.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  padding: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.btn-primary, .btn-secondary {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.08);
  color: #cbd5e0;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.btn-secondary:hover {
  background: rgba(255, 255, 255, 0.12);
  color: white;
}

.btn-primary:disabled, .btn-secondary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

@media (max-width: 768px) {
  .list-content {
    padding: 1.5rem;
  }

  .list-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .search-box {
    width: 100%;
  }

  .announcement-header {
    flex-direction: column;
    gap: 0.5rem;
  }

  .announcement-meta {
    align-items: flex-start;
  }

  .announcement-footer {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .announcement-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .modal-content {
    width: 95%;
    margin: 1rem;
  }
}
</style>